package cn.edu.gzhu.workOrderManagement.controller;

import cn.edu.gzhu.workOrderManagement.constants.MessageConstant;
import cn.edu.gzhu.workOrderManagement.properties.FileProperties;
import cn.edu.gzhu.workOrderManagement.properties.JwtProperties;
import cn.edu.gzhu.workOrderManagement.result.Result;
import cn.edu.gzhu.workOrderManagement.util.JwtUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/file")
@Tag(name = "文件接口")
public class FileUploadController {

    @Autowired
    private JwtProperties jwtProperties;
    private static final Tika tika = new Tika();
    private final FileProperties fileProperties;
    private List<String> allowedFileTypes;

    @Autowired
    public FileUploadController(FileProperties fileProperties) {
        this.fileProperties = fileProperties;
    }

    /**
     * Spring 初始化 Bean 时执行，加载允许的文件类型
     */
    @PostConstruct
    private void loadAllowedFileTypes() throws IOException {
        allowedFileTypes = new ArrayList<>();
        String filePath = fileProperties.getFileWhiteListPath(); // 使用自动装配的配置
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] types = line.split(","); // 逗号分隔
            for (String type : types) {
                allowedFileTypes.add(type.trim());
            }
        }

    }

    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE,value = "/upload")
    @Operation(summary = "文件上传")
    public Result fileUpload(@RequestHeader String token, @RequestParam("file") MultipartFile file) throws IOException {
        if ( file==null ||file.isEmpty()) {
            return Result.error(MessageConstant.FILE_INVALID);
        }
        //校验文件类型

        //String type = tika.detect(file.getInputStream());
        String contentType = file.getContentType();
        String[] split1 = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        if (split1.length<2){
            return Result.error(MessageConstant.FILE_INVALID);
        }
        String type = split1[split1.length - 1];
        if (contentType == null) {
            return Result.error(MessageConstant.FILE_INVALID);
        }
        String[] split = contentType.split("/");
        String fileType = split[split.length - 1];
        if (!allowedFileTypes.contains(fileType)) {
            return Result.error(MessageConstant.FILE_TYPE_NOT_ALLOWED);
        }

        // 生成文件名：token的第一部分+日期 + UUID
        String[] splitToken = token.split("\\.");
        String randomUUID = UUID.randomUUID().toString();
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());

        String fileName = splitToken[2] +"=="+ today + "==" + randomUUID + "." + type;

        // 确保目录存在
        File savePath = new File(fileProperties.getFileSavePath() + today + "/");
        if (!savePath.exists() && !savePath.mkdirs()) {
            return Result.error(MessageConstant.DIR_MAKE_ERROR);
        }

        // 保存文件
        File saveFile = new File(savePath.getAbsoluteFile(), fileName);
        file.transferTo(saveFile);

        return Result.success(fileName);
    }

    @PostMapping("/delete")
    @Operation(summary = "删除文件")
    public Result deleteFile(@RequestHeader String token,@RequestBody String fileName) {
        if (fileName.startsWith("\"")) {
            fileName = fileName.substring(1);
        }
        if (fileName.endsWith("\"")) {
            fileName = fileName.substring(0,fileName.length() - 1);
        }
        String[] splitToken = token.split("\\.");
        String[] split = fileName.split("==");
        if (!split[0].equals(splitToken[2])) {
            return Result.error(MessageConstant.PERMISSION_DENIED);
        }
        File savePath = new File(fileProperties.getFileSavePath() + split[1]+"/");
        if (!savePath.exists()) {
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        File file = new File(savePath,fileName);
        if (!file.exists()) {
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        if (!file.isFile()){
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        boolean res = file.delete();
        if (!res){
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        return Result.success();
    }

    @GetMapping("/get")
    @Operation(summary = "获取文件")
    public ResponseEntity<Resource> getFile(@RequestHeader String token, String fileName) throws IOException {
        String[] split = fileName.split("==");
        String savePath = fileProperties.getFileSavePath() + split[1]+"/";
        File file = new File(savePath,fileName);
        if (!file.exists()) {
            return ResponseEntity.notFound().build() ;
        }
        Path filePath = file.toPath();
        Resource resource = new PathResource(filePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, Files.probeContentType(filePath))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + file.getName() + "\"")
                .body(resource);
    }

}
